# For Loop

We have now seen the while loop in C++ . Next we will look at for loops.

The structure of a for loop is as follows

for(STATEMENT1 ; STATEMENT2 ; STATEMENT3)
{
    //code to be executed at every loop iteration
}

A for loop takes 3 statements separated by a semicolon.

STATEMENT1 is a C++ statement that runs before the for loop starts. Here we usually declare and initialize a variable that we will use to keep track of the number of iterations in the loop.

STATEMENT2 is a logic statement that gets checked at every loop iteration. If the statement is true then the loop iteration will start.

STATEMENT3 is a C++ statement that runs at the end of each loop iteration.

For example

for(int i=0; i < 10; i++)
{
    //code inside for loop
}

Before the loop starts, the for loop will execute the first statement

int i=0;

which is declaring a variable called i and initializing its value to 0.

The second statement is checking if i is less than 10 before every loop iteration. For the first iteration, this statement will be true because i is 0. So the for loop will execute the code inside of it for one iteration.

The third statement is incrementing the value of i. Remember from Arithmetic Operations Chapter, i++ will increment the variable i by 1. This statement will run after each loop iteration is done executing.

At this point, the second statement will be checked again to know if we can start another iteration or if the for loop should finish. After the first iteration the value of i became 1. This is still less than 10 so the loop will go through another iteration.

How many times will this for loop output "Hello World" to the Serial?

for(int i=0; i < 5; i++)
{
    Serial.println("Hello World");
}

Hello World is printed 5 times.

i is starting at 0 and at the end of every iteration, i is incrementing.

Iteration 1:    0 < 5 -> Hello World

Iteration 2:    1 < 5 -> Hello World

Iteration 3:    2 < 5 -> Hello World

Iteration 4:    3 < 5 -> Hello World

Iteration 5:    4 < 5 -> Hello World

Iteration 6:    5 < 5 FALSE TERMINATE LOOP

# Exercise

Homework

The code below is missing the condition of the for loop. Replace STATEMENT2 with a logical condition that if checks i is less than or equal to 10.

Note

Notice how we are using the variable i inside the for loop scope. We are printing the value of i at every iteration.